package cm.mefobe.android.telecomcost.view;

import java.util.ArrayList;

import cm.mefobe.android.telecomcost.adapter.TimePeriodAdapter;
import cm.mefobe.android.telecomcost.entities.TimePeriod;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

public class TimePeriodSpinner extends Spinner {
	
	private ArrayList<TimePeriod> periode_list;
	private Context _context;
	private SpinnerAdapter _adapter;
	private TimePeriod _selectedPeriod;
	
	private void setList()
	{
		Log.i("TimePeriodSpinner","setting the TimePeriodSpinner list...");
		if(_context != null)
		{
			periode_list = new ArrayList<TimePeriod>();
			periode_list.add(TimePeriod.SECOND);
			periode_list.add(TimePeriod.MINUTE);
			periode_list.add(TimePeriod.HOUR);
			periode_list.add(TimePeriod.DAY);
			periode_list.add(TimePeriod.WEEK);
			periode_list.add(TimePeriod.MONTH);
			periode_list.add(TimePeriod.YEAR);
			
			setPrompt("Select a period");
		
			_adapter = new TimePeriodAdapter(
					_context,android.R.layout.select_dialog_singlechoice,
					periode_list);			
		}	
		else
		{
			Log.i("TimePeriodSpinner","cannot set the adapter of the TimePeriodSpinner...the context is null");
		}
	}	
	
	@Override
	public void setAdapter(SpinnerAdapter adapter) {	
		setList();
		super.setAdapter(_adapter);			
	}

	@Override
	public SpinnerAdapter getAdapter() {		
		return _adapter;
	}

	public TimePeriodSpinner(Context context) {
		super(context);
		_context = context;			
	}

	public TimePeriodSpinner(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		_context = context;			
	}

	public TimePeriodSpinner(Context context, AttributeSet attrs) {
		super(context, attrs);
		_context = context;			
	}	

	@Override
	public void setSelection(int position) {
		_selectedPeriod = (TimePeriod) _adapter.getItem(position);	
		super.setSelection(position);
	}

	public TimePeriod getPeriod() {		
		return _selectedPeriod;
	}

	public void setPeriod(TimePeriod period) {
		int index = 0;
		
		while(index < periode_list.size())
		{
			TimePeriod _period = periode_list.get(index);
			if(_period.index() == period.index())
			{
				setSelection(index, true);
			}
		}		
	}	
}
